const User = require('../models/user')
const setOutputModel = require('../tools/setOutput')
const standardObj = setOutputModel.standardObj
const decryptByDES = require('../tools/crypto').decryptByDES
const userController = require('../controllers/user')
const jwt = require('jsonwebtoken')
const {TOKEN_KEY, TOKEN_EXPIRE} = require('../config')


class LoginController {
  async login(ctx, next) {
    ctx.verifyParams({
      userName: { type: "string", required: true },
      password: { type: "string", required: true }
    })
    let userName = decryptByDES(ctx.request.body.userName, TOKEN_KEY)
    let password = decryptByDES(ctx.request.body.password, TOKEN_KEY)

    const user = await User.find({
      userName: userName
    }).limit(1).lean()
    let output

    if (!user.length) {
      output = { 
        data: null,
        code: 400,
        msg: '无对应用户'
      }
    } else {  
      if (password !== user[0].password) {
        output = { 
          data: null,
          code: 400,
          msg: '用户名或密码错误'
        }
      } else {
        const data = {
          ...user[0],
          time: Date.now(),
          timeout: Date.now() + 60 * 1000 * TOKEN_EXPIRE
        }  
        const token = jwt.sign(data, TOKEN_KEY)
        output = { 
          data: {
            userInfo: standardObj(user[0]),
            token: token
          },
          code: 0,
          msg: '成功' 
        }
      } 
    } 
    

    ctx.response.body = output
  }

  async signin(ctx, next) {
    ctx.verifyParams({
      userName: { type: "string", required: true },
      password: { type: "string", required: true },
      name: { type: 'string', required: false }
    }) 
    let obj = {...ctx.request.body}
    obj.userName = decryptByDES(ctx.request.body.userName, TOKEN_KEY)
    obj.password = decryptByDES(ctx.request.body.password, TOKEN_KEY)

    const [err, data] = await to(userController.addUser(obj))
    if(err) return ctx.throw(500, err)
    let output
    const _data = {
      ...data,
      time: Date.now(),
      timeout: Date.now() + 60 * 1000 * TOKEN_EXPIRE
    }  
    const token = jwt.sign(_data, TOKEN_KEY)
    output = { 
      data: {
        userInfo: standardObj(data),
        token: token
      },
      code: 0,
      msg: '成功' 
    }

    ctx.response.body = output
  }
}

module.exports = new LoginController()